package com.linshidream.intrachat.simplenio.packet.context;

import com.linshidream.intrachat.simplenio.packet.handler.MessageCodec;
import com.linshidream.intrachat.simplenio.packet.handler.PacketHandler;
import com.linshidream.intrachat.simplenio.packet.handler.PacketWriter;

import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created on 2025/7/31 18:15
 *
 * @author linshidream
 * @version 1.0.0
 * @description 连接上下文
 */

public class DefaultConnectionContext implements ConnectionContext {

    private final SocketChannel channel;

    private Selector selector;

    private PacketWriter packetWriter;

    private final MessageCodec codec;

    private final PacketHandler handler;

    private final ByteBuffer buffer;


    public DefaultConnectionContext(SocketChannel channel, Selector selector, MessageCodec codec, PacketHandler handler) {
        this.channel = channel;
        this.selector = selector;
        this.codec = codec;
        this.handler = handler;
        this.packetWriter = new PacketWriter(channel, selector);

        this.buffer = ByteBuffer.allocate(8 * 1024);
    }


    public DefaultConnectionContext(SocketChannel channel, MessageCodec codec, PacketHandler handler) {
        this.channel = channel;
        this.codec = codec;
        this.handler = handler;

        this.buffer = ByteBuffer.allocate(8 * 1024);
    }

    @Override
    public Selector selector() {
        return selector;
    }

    @Override
    public PacketWriter writer() {
        return packetWriter;
    }

    @Override
    public SocketChannel channel() {
        return channel;
    }

    @Override
    public MessageCodec codec() {
        return codec;
    }

    @Override
    public PacketHandler handler() {
        return handler;
    }

    @Override
    public ByteBuffer accumulate(ByteBuffer buffer) {
        // 当前连接通道下的 缓冲区未读数据 + buffer未读数据
        return this.buffer.put(buffer);
    }
}
